<template>
  <div class="main_box" style="padding:10px">
    <div class="add_wrap">
      <div class="tit">
        <h2>{{ dataForm.villageId ? "编辑小区信息" : "新增小区" }}</h2>
        <el-button type="success" plain size="small" icon="fa fa-mail-forward" @click="returnList">返回</el-button>
      </div>
      <el-form :model="dataForm" ref="dataForm" label-width="200px" :rules="roleRules">
        <el-row>
          <el-form-item label="小区" width="300" align="center" prop="villageName">
            <el-input v-model="dataForm.villageName" placeholder="请输入小区名称"></el-input>
          </el-form-item>
          <el-form-item label="小区排序(正序)" align="center" prop="sort">
            <el-input type="number" v-model="dataForm.sort" placeholder="小区显示优先级"></el-input>
          </el-form-item>
          <el-form-item label="地区" prop="streetIds">
            <Region :streetValues="dataForm.streetIds" @regionChange="handleItemChange" :isChangeOnSelect="true"></Region>
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="dataForm.address" placeholder="xx路xx号xx栋"></el-input>
          </el-form-item>
          <el-form-item label="经度" prop="longitude">
            <el-input type="number" v-model="dataForm.longitude"></el-input>
          </el-form-item>
          <el-form-item label="纬度" prop="latitude">
            <el-input type="number" v-model="dataForm.latitude"></el-input>
            <el-button type="text" @click="getLngLat(1)">百度地图</el-button>
            <el-button type="text" @click="getLngLat(2)">腾讯地图</el-button>
          </el-form-item>
          <el-form-item label="开发员" prop="developerId" v-if="userRole == 1 && detailRole == 1">
            <el-select v-model="dataForm.developerId" placeholder="请选择开发员">
              <el-option v-for="item in roleList" :value="item.id" :label="item.name" :key="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="推广员" prop="promoterId" v-if="userRole == 1 && detailRole == 1">
            <el-select v-model="dataForm.promoterId" placeholder="请选择推广员" multiple>
              <el-option v-for="item in roleList" :value="item.id" :label="item.name" :key="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="维护员" prop="keeperId" v-if="userRole == 1 && detailRole == 1">
            <el-select v-model="dataForm.keeperId" placeholder="请选择维护员">
              <el-option v-for="item in roleList" :value="item.id" :label="item.name" :key="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="安保呼叫器编号" prop="beeperCode">
            <el-input v-model="dataForm.beeperCode"></el-input>
          </el-form-item>
          <el-form-item label="物业名称" prop="pmcName">
            <el-input v-model="dataForm.pmcName"></el-input>
          </el-form-item>
          <el-form-item label="物业电话" prop="pmcPhone">
            <el-input v-model="dataForm.pmcPhone"></el-input>
          </el-form-item>
          <el-form-item label="物业备用电话" prop="pmcPhoneTwo">
            <el-input v-model="dataForm.pmcPhoneTwo"></el-input>
          </el-form-item>
          <el-form-item label="物业收费周期" prop="feePeriod">
            <el-checkbox-group v-model="dataForm.feePeriod">
              <el-checkbox label="1">月付</el-checkbox>
              <el-checkbox label="2">季付</el-checkbox>
              <el-checkbox label="3">年付</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="开锁人名称" prop="unlockName">
            <el-input v-model="dataForm.unlockName"></el-input>
          </el-form-item>
          <el-form-item label="开锁电话" prop="unlockPhone">
            <el-input v-model="dataForm.unlockPhone" type="number"></el-input>
          </el-form-item>
          <el-form-item label="开锁备用电话" prop="unlockSparePhone">
            <el-input v-model="dataForm.unlockSparePhone" type="number"></el-input>
          </el-form-item>
          <el-form-item label="报警时是否联系紧急联系人" prop="fastLinkFlag">
            <el-radio-group v-model="dataForm.fastLinkFlag">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="120行车路线" prop="sosRoute">
            <el-input v-model="dataForm.sosRoute"></el-input>
          </el-form-item>
          <el-form-item label="120电话" prop="sosPhone">
            <el-input type="number" v-model="dataForm.sosPhone"></el-input>
          </el-form-item>
          <el-form-item label="小区介绍" prop="introduce">
            <el-input type="textarea" v-model="dataForm.introduce"></el-input>
          </el-form-item>
          <el-form-item prop="villageImage" label="小区地图图片">
            <upload-img class="upload-img" @uploadFileList="getVillageImage" folder="aedSitefile">
              <img v-if="dataForm.villageImage" width="100%" :src="dataForm.villageImage" alt="" />
              <div class="tip">
                <i class="el-icon-upload" v-if="!dataForm.villageImage"></i>
                <div v-if="!dataForm.villageImage" class="el-upload__text">
                  将图片拖到此处，或<em>点击上传</em>
                </div>
              </div>
            </upload-img>
          </el-form-item>
        </el-row>
        <div class="tit">
          <h2>小区楼宇结构图</h2>
        </div>
        <el-row>
          <el-row style="width: 98%;margin: 0 auto;">
            <UploadOssFile class="upload-oss-file-c" :list="fileList" :isSelect="false" :limit="10"
              @getImgVideo="getImgVideo" folder="serverImg"></UploadOssFile>
          </el-row>
        </el-row>
        <el-row>
          <el-form-item>
            <el-button plain type="primary" @click="sureClick">保 存</el-button>
            <el-button plain @click="returnList">取 消</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
  </div>
</template>

<script>
import * as message from "@/constants/message";
import Region from "@/components/Region";
import VillageApi from "@/api/address/village";
import LoginApi from "@/api/system/login";
import { getStorage } from "@/utils/auth";
import { USER_INFO } from "@/constants/storeName";
import UploadImg from "@/components/UploadImg";
import UploadOssFile from "../../components/UploadOssFile.vue";

export default {
  data() {
    return {
      userRole: "",
      detailRole: "",
      dataForm: {
        villageId: "",
        villageName: "",
        sort: "",
        longitude: "",
        latitude: "",
        streetIds: [],
        provinceId: "",
        provinceName: "",
        cityId: "",
        cityName: "",
        areaId: "",
        areaName: "",
        streetId: "",
        streetName: "",
        address: "",
        developerId: "", //开发员id
        promoterId: [], //推广员id,有多个,
        keeperId: "",
        pmcName: "", //物业名称
        pmcPhone: "", //物业常用电话
        pmcPhoneTwo: "", //物业备用电话
        sosRoute: "",
        sosPhone: "",
        introduce: "",
        linkWxAppUrl: "",
        villageImage: "",
        beeperCode: "",
        buildStructImgs: [],
        feePeriod: [],
        fastLinkFlag: 1,
        unlockName: '',
        unlockPhone: '',
        unlockSparePhone: '',
      },
      loadingIns: false,
      roleRules: {
        streetIds: [
          { required: true, message: "请选择所在地区", trigger: "change" }
        ],
        villageName: [
          { required: true, message: "请输入小区名称", trigger: "blur" }
        ],
        villageImage: [
          { required: true, message: "图片必传", trigger: "blur" }
        ],
        address: [
          { required: true, message: "请输入详细地址", trigger: "blur" }
        ],
        pmcPhone: [
          {
            pattern: /^\d+$/,
            message: "物业电话号码格式错误",
            trigger: "blur"
          }
        ],
        pmcPhoneTwo: [
          {
            pattern: /^\d+$/,
            message: "物业备用电话号码格式错误",
            trigger: "blur"
          }
        ],
        longitude: [{ required: true, message: "请输入经度", trigger: "blur" }],
        latitude: [{ required: true, message: "请输入维度", trigger: "blur" }]
      },
      roleList: [],
      fileList: []
    };
  },
  components: {
    Region,
    UploadImg,
    UploadOssFile
  },
  mounted() {
    this.init();
  },
  methods: {
    init() {
      this.getRoleInfoList();
      // 获取用户的角色信息
      this.userRole = getStorage(USER_INFO).userRole;
      this.detailRole = getStorage(USER_INFO).detailRole;
      if (this.$route.query.id) {
        this.dataForm.villageId = this.$route.query.id;
        this.getData();
      }
    },

    keydown(e) {
      if (e.keyCode === 32) {
        e.returnValue = false;
      }
    },

    getLngLat(type) {
      if (type === 1) {
        window.open(
          "https://api.map.baidu.com/lbsapi/getpoint/index.html",
          "_blank"
        );
      } else {
        window.open("https://lbs.qq.com/getPoint", "_blank");
      }
    },

    getData() {
      VillageApi.getVillageInfo({
        id: this.dataForm.villageId
      }).then(res => {
        this.$Utils.bindingBean(this.dataForm, res.data);
        //图片深度克隆一下

        if (this.dataForm.buildStructImgs != null && this.dataForm.buildStructImgs != '') {
          this.fileList = JSON.parse(
            JSON.stringify(this.dataForm.buildStructImgs || '')
          )
            .split(",")
            .map(url => ({ url, type: 1 }));
        }
        console.log(this.dataForm.feePeriod,"this.dataForm.feePeriod")
        if (this.dataForm.feePeriod && this.dataForm.feePeriod.length>0) {
          this.dataForm.feePeriod = this.dataForm.feePeriod.split(',');
        } else {
          this.dataForm.feePeriod = [];
        }

        // 传过来的是字符串需要分割为数组且要化为数字
        res.data.promoterId
          ? (this.dataForm.promoterId = res.data.promoterId
            .split(",")
            .map(item => Number(item)))
          : "";
        this.dataForm.streetIds = [
          this.dataForm.provinceId,
          this.dataForm.provinceName,
          this.dataForm.cityId,
          this.dataForm.cityName,
          this.dataForm.areaId,
          this.dataForm.areaName,
          this.dataForm.streetId,
          this.dataForm.streetName
        ];
      });
    },

    getRoleInfoList() {
      LoginApi.roleInfoList().then(res => {
        this.roleList = res.data;
      });
    },

    sureClick() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          // 需要判断地区是否是三级或者四级，如果不是就不许提交
          let value = this.dataForm.streetIds;
          for (let i = 0; i < value.length; i++) {
            if (value[i]) {
              continue;
            } else if (i < 3) {
              this.$message.error("地区至少选至三级");
              return;
            }
          }
          this.$confirm(
            message.MSG_CONFIRM_SAVE_ALTER,
            message.TITLE_PROMPT,
            {}
          ).then(() => {
            if (this.dataForm.villageId) {
              this.editData();
            } else {
              this.addData();
            }
          });
        }
      });
    },

    addData() {
      let param = {
        villageName: this.dataForm.villageName,
        sort: this.dataForm.sort,
        longitude: this.dataForm.longitude,
        latitude: this.dataForm.latitude,
        provinceId: this.dataForm.provinceId,
        provinceName: this.dataForm.provinceName,
        cityId: this.dataForm.cityId,
        cityName: this.dataForm.cityName,
        areaId: this.dataForm.areaId,
        areaName: this.dataForm.areaName,
        streetId: this.dataForm.streetId,
        streetName: this.dataForm.streetName,
        address: this.dataForm.address,
        developerId: this.dataForm.developerId,
        promoterId:
          this.dataForm.promoterId.length > 0
            ? this.dataForm.promoterId.join(",")
            : "",
        keeperId: this.dataForm.keeperId,
        pmcName: this.dataForm.pmcName,
        pmcPhone: this.dataForm.pmcPhone,
        pmcPhoneTwo: this.dataForm.pmcPhoneTwo,
        sosRoute: this.dataForm.sosRoute,
        sosPhone: this.dataForm.sosPhone,
        villageImage: this.dataForm.villageImage,
        buildStructImgs: this.dataForm.buildStructImgs ? this.dataForm.buildStructImgs.map(item => item.url).join(",") : '',
        feePeriod: this.dataForm.feePeriod.join(','),
        fastLinkFlag: this.dataForm.fastLinkFlag,
        beeperCode: this.dataForm.beeperCode,
        unlockName: this.dataForm.unlockName,
        unlockPhone: this.dataForm.unlockPhone,
        unlockSparePhone: this.dataForm.unlockSparePhone,
      };
      VillageApi.addVillage(param).then(res => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },

    editData() {
      let param = {
        villageId: this.dataForm.villageId,
        villageName: this.dataForm.villageName,
        sort: this.dataForm.sort,
        longitude: this.dataForm.longitude,
        latitude: this.dataForm.latitude,
        provinceId: this.dataForm.provinceId,
        provinceName: this.dataForm.provinceName,
        cityId: this.dataForm.cityId,
        cityName: this.dataForm.cityName,
        areaId: this.dataForm.areaId,
        areaName: this.dataForm.areaName,
        streetId: this.dataForm.streetId,
        streetName: this.dataForm.streetName,
        address: this.dataForm.address,
        developerId: this.dataForm.developerId,
        promoterId:
          this.dataForm.promoterId.length > 0
            ? this.dataForm.promoterId.join(",")
            : "",
        keeperId: this.dataForm.keeperId,
        pmcName: this.dataForm.pmcName,
        pmcPhone: this.dataForm.pmcPhone,
        pmcPhoneTwo: this.dataForm.pmcPhoneTwo,
        sosRoute: this.dataForm.sosRoute,
        sosPhone: this.dataForm.sosPhone,
        introduce: this.dataForm.introduce,
        villageImage: this.dataForm.villageImage,
        buildStructImgs: this.dataForm.buildStructImgs ? this.dataForm.buildStructImgs.map(item => item.url).join(",") : '',
        feePeriod: this.dataForm.feePeriod.join(','),
        fastLinkFlag: this.dataForm.fastLinkFlag,
        beeperCode: this.dataForm.beeperCode,
        unlockName: this.dataForm.unlockName,
        unlockPhone: this.dataForm.unlockPhone,
        unlockSparePhone: this.dataForm.unlockSparePhone,
      };
      VillageApi.editVillage(param).then(data => {
        this.$Utils.notifySuccess();
        this.returnList();
      });
    },

    handleItemChange(val) {
      this.dataForm.provinceId = val.provinceId;
      this.dataForm.provinceName = val.provinceName;
      this.dataForm.cityId = val.cityId;
      this.dataForm.cityName = val.cityName;
      this.dataForm.areaId = val.areaId;
      this.dataForm.areaName = val.areaName;
      this.dataForm.streetId = val.streetId;
      this.dataForm.streetName = val.streetName;
      if (val.provinceId) {
        this.dataForm.streetIds = [
          val.provinceId,
          val.cityId,
          val.areaId,
          val.streetId
        ];
      } else {
        this.dataForm.streetIds = [];
      }
    },

    returnList() {
      this.$store.dispatch("delView", this.$route);
      this.$router.back();
    },

    getVillageImage(val) {
      if (val.length > 0) {
        this.$Utils.notifySuccess("上传成功");
      }
      this.dataForm.villageImage = val[0];
    },

    // 获取上传的文件列表
    getImgVideo(val) {
      this.dataForm.buildStructImgs = val;
    }
  }
};
</script>
<style lang="scss" scoped>
@import "@/assets/css/views/add.scss";

.upload-img {
  &::v-deep .el-upload {
    width: 100%;

    .el-upload-dragger {
      width: 100%;
      display: flex;
      justify-content: space-around;
      align-items: center;

      .tip {
        padding-bottom: 30px;
      }
    }
  }
}

.upload-oss-file-c {
  &::v-deep .img-video-wrapper {
    .drag {
      .content {
        margin-bottom: 10px;
      }
    }
  }
}
</style>
